package com.heima.search.listener;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.heima.common.constatns.ArticleConstants;
import com.heima.common.constatns.ArticleMessageConstants;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.cert.ocsp.Req;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class SyncArticleListener {

    //创建索引
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @KafkaListener(topics = ArticleMessageConstants.ARTICLE_ES_SYNC_TOPIC)
    public void onMessage(String message){

        if (StringUtils.isNotBlank(message)){
            log.info("[创建索引]SyncArticleListener接收到的消息为，message={}",message);
            SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);

            IndexRequest indexRequest = new IndexRequest("app_info_article");
            indexRequest.id(searchArticleVo.getId().toString()).source(message, XContentType.JSON);

            try {
                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                log.info("同步成功");
            } catch (IOException e) {
                e.printStackTrace();
                log.error("同步错误={}",e);
            }
        }

    }
}
